package com.uyii.springbootelasticsearch.demos.web;

import org.elasticsearch.index.query.MatchQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class ProductService {

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    public Product saveProduct(Product product) {
        productRepository.save(product);
        return elasticsearchRestTemplate.save(product);
    }

    public Optional<Product> findProductById(String id) {
        return productRepository.findById(id);
    }

    public Iterable<Product> findAllProducts() {
        return productRepository.findAll();
    }

    public void deleteProductById(String id) {
        productRepository.deleteById(id);
    }

    public SearchHits<Product> searchProducts(String keyword) {
        // match 查询，支持简单的模糊匹配
        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
                .withQuery(new MatchQueryBuilder("name", keyword))
                .build();

        return elasticsearchRestTemplate.search(nativeSearchQuery, Product.class);
    }
}